using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Guide;
using B.S.NewMedical.Api.Read.DTOS.Guide;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Guide
{
    /// <summary>
    /// 获取就医指南分类处理器
    /// </summary>
    public class GetGuideCategoriesHandler : IRequestHandler<GetGuideCategoriesCommand, ApiResult<List<GuideCategoryDto>>>
    {
        private readonly IBaseRepository<GuideCategory> _categoryRepository;
        private readonly ILogger<GetGuideCategoriesHandler> _logger;
        private readonly IMapper _mapper;

        public GetGuideCategoriesHandler(
            IBaseRepository<GuideCategory> categoryRepository,
            ILogger<GetGuideCategoriesHandler> logger,
            IMapper mapper)
        {
            _categoryRepository = categoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<GuideCategoryDto>>> Handle(GetGuideCategoriesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取就医指南分类列表");

                // 获取所有未删除的分类，按排序字段排序
                var categories = await _categoryRepository.GetAll()
                    .Where(c => !c.IsDeleted)
                    .OrderBy(c => c.Sort)
                    .ToListAsync(cancellationToken);

                // 使用AutoMapper映射到DTO
                var result = _mapper.Map<List<GuideCategoryDto>>(categories);

                return new ApiResult<List<GuideCategoryDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取就医指南分类列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取就医指南分类列表时发生异常");
                return new ApiResult<List<GuideCategoryDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取就医指南分类列表失败：" + ex.Message
                };
            }
        }
    }
} 